import React from 'react';
import { Result, Button } from 'antd';

interface ErrorBoundaryState {
    hasError: boolean;
    error?: Error;
}

interface ErrorBoundaryProps {
    children: React.ReactNode;
}

class ErrorBoundary extends React.Component<ErrorBoundaryProps, ErrorBoundaryState> {
    constructor(props: ErrorBoundaryProps) {
        super(props);
        this.state = { hasError: false };
    }

    static getDerivedStateFromError(error: Error): ErrorBoundaryState {
        return { hasError: true, error };
    }

    componentDidCatch(error: Error, errorInfo: React.ErrorInfo) {
        console.error('ErrorBoundary caught an error:', error, errorInfo);
    }

    render() {
        if (this.state.hasError) {
            return (
                <Result
                    status="error"
                    title="页面加载出错"
                    subTitle={`错误信息: ${this.state.error?.message || '未知错误'}`}
                    extra={[
                        <Button 
                            type="primary" 
                            key="reload"
                            onClick={() => window.location.reload()}
                        >
                            刷新页面
                        </Button>,
                        <Button 
                            key="back"
                            onClick={() => window.history.back()}
                        >
                            返回上页
                        </Button>
                    ]}
                />
            );
        }

        return this.props.children;
    }
}

export default ErrorBoundary;
